#include <stdlib.h>
#include "memory.h"
#include "list.h"
#include "hash_table.h"

static int hash_table_hash(int key, int hash_table_size);

hash_table_t* hash_table_construct(int hash_table_size)
{
	hash_table_t* hash_table = (hash_table_t*) my_malloc(sizeof(hash_table_t));
	int i = 0;
	hash_table->size = hash_table_size;
	hash_table->array = (list_node_t**) my_malloc(hash_table_size*sizeof(list_node_t*));
	for (i = 0; i < hash_table_size; i++)
		hash_table->array[i] = list_construction();
	return hash_table;
}

void hash_table_destruct(hash_table_t* hash_table)
{
	int i = 0;
	for (i = 0; i < hash_table->size; i++)
		list_destruct(hash_table->array[i]);
	free(hash_table->array);
	free(hash_table);
}

int hash_table_find(hash_table_t* hash_table, int key, int* value)
{
	int index = hash_table_hash(key, hash_table->size);
	list_node_t* list = list_find(hash_table->array[index], key);
	if (list == NULL) return 1;
	*value = list->value;
	return 0; 
}

int hash_table_add(hash_table_t* hash_table, int key, int value)
{
	int index = hash_table_hash(key, hash_table->size);
	list_node_t* list = list_find(hash_table->array[index], key);
	if (list != NULL)
	{
		list->key = key;
		list->value = value;
		return 1;
	}
	hash_table->array[index] = list_add(hash_table->array[index], key, value);
	return 0;
}

void hash_table_del(hash_table_t* hash_table, int key)
{
	int index = hash_table_hash(key, hash_table->size);
	list_node_t* list = list_find(hash_table->array[index], key);
	if (list != NULL)
		hash_table->array[index] = list_node_del(list);
}

int hash_table_hash(int key, int hash_table_size)
{
	return (key % hash_table_size); 	
}
